﻿using Bing.Maps;
using Callisto.Controls;
using DT.GoogleAnalytics.Metro;
using RWSBeeldbank.Common;
using RWSBeeldbank.Data;
using RWSBeeldbank.Utility;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Net;
using System.Threading.Tasks;
using Windows.ApplicationModel.DataTransfer;
using Windows.ApplicationModel.Resources;
using Windows.ApplicationModel.Store;
using Windows.Foundation;
using Windows.Foundation.Collections;
using Windows.Media.Capture;
using Windows.Storage;
using Windows.Storage.Streams;
using Windows.UI.Notifications;
using Windows.UI.Popups;
using Windows.UI.StartScreen;
using Windows.UI.Xaml;
using Windows.UI.Xaml.Controls;
using Windows.UI.Xaml.Controls.Primitives;
using Windows.UI.Xaml.Data;
using Windows.UI.Xaml.Input;
using Windows.UI.Xaml.Media;
using Windows.UI.Xaml.Navigation;
using RWSBeeldbank.DataModel;

// The Item Detail Page item template is documented at http://go.microsoft.com/fwlink/?LinkId=234232

namespace RWSBeeldbank
{
    /// <summary>
    /// A page that displays details for a single item within a group while allowing gestures to
    /// flip through other items belonging to the same group.
    /// </summary>
    public sealed partial class FullScreenItemDetailPage : LayoutAwarePage
    {
        public FullScreenItemDetailPage()
        {
            this.InitializeComponent();
        }

        /// <summary>
        /// Populates the page with content passed during navigation.  Any saved state is also
        /// provided when recreating a page from a prior session.
        /// </summary>
        /// <param name="navigationParameter">The parameter value passed to
        /// <see cref="Frame.Navigate(Type, Object)"/> when this page was initially requested.
        /// </param>
        /// <param name="pageState">A dictionary of state preserved by this page during an earlier
        /// session.  This will be null the first time a page is visited.</param>
        protected override void LoadState(Object navigationParameter, Dictionary<String, Object> pageState)
        {
            // Allow saved page state to override the initial item to display
            if (pageState != null && pageState.ContainsKey("SelectedItem"))
            {
                navigationParameter = pageState["SelectedItem"];
            }

            // TODO: Create an appropriate data model for your problem domain to replace the sample data
            var item = MediaObjectDataSource.GetItem((String)navigationParameter);
            this.DefaultViewModel["Group"] = item.Group;
            this.DefaultViewModel["Items"] = item.Group.Items;
            this.flipView.SelectedItem = item;

            // Register for DataRequested events
            DataTransferManager.GetForCurrentView().DataRequested += OnDataRequested;
        }

        /// <summary>
        /// Preserves state associated with this page in case the application is suspended or the
        /// page is discarded from the navigation cache.  Values must conform to the serialization
        /// requirements of <see cref="SuspensionManager.SessionState"/>.
        /// </summary>
        /// <param name="pageState">An empty dictionary to be populated with serializable state.</param>
        protected override void SaveState(Dictionary<String, Object> pageState)
        {
            var selectedItem = (MediaObjectDataItem)this.flipView.SelectedItem;
            if (selectedItem != null)
                pageState["SelectedItem"] = selectedItem.UniqueId;

            // Deregister the DataRequested event handler
            DataTransferManager.GetForCurrentView().DataRequested -= OnDataRequested;

            // Dispose the handler so it can be added when LoadState fires again
            _dataRequestHandler = null;
        }

        void OnDataRequested(DataTransferManager sender, DataRequestedEventArgs args)
        {
            var request = args.Request;
            var item = (MediaObjectDataItem)this.flipView.SelectedItem;
            
            // Fill request with MediaObject Data
            request = Tools.SetMessageRequest(item, request);
        }
        
        private async void OnPinMediaObjectButtonClicked(object sender, RoutedEventArgs e)
        {
            var item = (MediaObjectDataItem)this.flipView.SelectedItem;
            var uniqueId = item.UniqueId.Replace("|", "_");
            var activationString = item.TypeId.ToString() + "|" + item.UniqueId;
            var uri = await Tools.GetUriLocalImageAsync(item.TileImagePath.AbsoluteUri, uniqueId);

            var tile = new SecondaryTile(
                    uniqueId,                        // Tile ID
                    item.AltTitle,                   // Tile short name
                    item.Title,                      // Tile display name
                    activationString,                // Activation argument
                    TileOptions.ShowNameOnLogo,      // Tile options
                    uri                              // Tile logo URI
                );

            await tile.RequestCreateAsync();
        }

        private async void OnBrowseToMediaObjectButtonClicked(object sender, RoutedEventArgs e)
        {
            var item = (MediaObjectDataItem)this.flipView.SelectedItem;
            // Create the URI to launch from a string. 
            var uri = new Uri(item.DirectLink);

            // Launch the URI. 
            await Windows.System.Launcher.LaunchUriAsync(uri);
        }

        private void OnDownloadMediaObjectButtonClicked(object sender, RoutedEventArgs e)
        {
            var resourceLoader = new ResourceLoader();

            // Create a menu containing two items
            var menu = new Menu();
            var item1 = new MenuItem { Text = resourceLoader.GetString("appBarSmallPhoto") };
            item1.Tapped += OnSaveSmallSizeMediaObjectButtonClicked;
            menu.Items.Add(item1);
            var item2 = new MenuItem { Text = resourceLoader.GetString("appBarMediumPhoto") };
            item2.Tapped += OnSaveLargeSizeMediaObjectButtonClicked;
            menu.Items.Add(item2);
            var item3 = new MenuItem { Text = resourceLoader.GetString("appBarOriginalPhoto") };
            item3.Tapped += OnSaveOriginalSizeMediaObjectButtonClicked;
            menu.Items.Add(item3);

            // Show the menu in a flyout anchored to the Brag button
            var flyout = new Flyout();
            flyout.Placement = PlacementMode.Top;
            flyout.HorizontalAlignment = HorizontalAlignment.Left;
            flyout.HorizontalContentAlignment = HorizontalAlignment.Left;
            flyout.PlacementTarget = DownloadMediaObjectButton;
            flyout.Content = menu;
            flyout.IsOpen = true;
        }

        private async void OnSaveSmallSizeMediaObjectButtonClicked(object sender, RoutedEventArgs e)
        {
            // Retrieve the image and store it in the local PicturesLibrary
            var item = (MediaObjectDataItem)this.flipView.SelectedItem;
            await Tools.StoreImageInPicturesLibraryAsync(item, 1);
            await MediaObjectDataSource.SetRatingAsync(3, item.Id);
            PageAppBar.IsOpen = false;
        }

        private async void OnSaveLargeSizeMediaObjectButtonClicked(object sender, RoutedEventArgs e)
        {
            // Retrieve the image and store it in the local PicturesLibrary
            var item = (MediaObjectDataItem)this.flipView.SelectedItem;
            await Tools.StoreImageInPicturesLibraryAsync(item, 2);
            await MediaObjectDataSource.SetRatingAsync(4, item.Id);
            PageAppBar.IsOpen = false;
        }

        private async void OnSaveOriginalSizeMediaObjectButtonClicked(object sender, RoutedEventArgs e)
        {
            // Retrieve the image and store it in the local PicturesLibrary
            var item = (MediaObjectDataItem)this.flipView.SelectedItem;
            await Tools.StoreImageInPicturesLibraryAsync(item, 3);
            await MediaObjectDataSource.SetRatingAsync(5, item.Id);
            PageAppBar.IsOpen = false;
        }

        private void fullScreenButtonClicked(object sender, RoutedEventArgs e)
        {
            // Navigate to the appropriate destination page, configuring the new page
            // by passing required information as a navigation parameter
            var itemId = ((MediaObjectDataItem)this.flipView.SelectedItem).UniqueId;
            this.Frame.Navigate(typeof(FullScreenItemDetailPage), itemId);
        }

        private void Grid_PointerMoved(object sender, PointerRoutedEventArgs e)
        {
            this.backButton.Visibility = Windows.UI.Xaml.Visibility.Visible;
        }

        private void Grid_PointerPressed(object sender, PointerRoutedEventArgs e)
        {
            this.backButton.Visibility = Windows.UI.Xaml.Visibility.Collapsed;
        }

        private async void OnSetLockScreenButtonClicked(object sender, RoutedEventArgs e)
        {
            // Retrieve the current image
            var item = (MediaObjectDataItem)this.flipView.SelectedItem;

            await Tools.PutImageOnLockScreen(item);
        }

        private void ItemDetailButtonClicked(object sender, RoutedEventArgs e)
        {
            // Navigate to the appropriate destination page, configuring the new page
            // by passing required information as a navigation parameter
            var itemId = ((MediaObjectDataItem)this.flipView.SelectedItem).UniqueId;
            this.Frame.Navigate(typeof(ItemDetailPage), itemId);
        }

        private void flipView_SelectionChanged(object sender, SelectionChangedEventArgs e)
        {
            // Retrieve the current image
            var item = (MediaObjectDataItem)this.flipView.SelectedItem;

            if ((myMap != null) && (item.Latitude != 0.0))
            {
                myMap.Visibility = Visibility.Visible;

                // Creating a location object, this is used to set the location of the pin and center the map
                Bing.Maps.Location location = new Bing.Maps.Location
                {
                    Latitude = item.Latitude,
                    Longitude = item.Longitude
                };

                // Set the map to be centered on that location
                myMap.SetView(location, item.GoogleZoom);

                // Create a pushpin and reposition it on the map at location
                MapLayer.SetPosition(pushPin, location);
            }
            else
                myMap.Visibility = Visibility.Collapsed;

            if ((sender as FlipView).Visibility == Visibility.Visible)
                AnalyticsHelper.TrackPageView(pageRoot.ToString());
        }

    }
}
